<?php
    $sid = $_COOKIE[$cookieName];
    $expireTime = time() + $sessionPeriod;
    $uid = getUid($sid);
    if ($uid && $_POST['quit'] == 'quit') {
        deleteSession($sid);
        $uid = 0;
    }
    if ($uid) {
        $authorized = getAuthorized($uid);
        prolongateSession($sid, $expireTime);
    } else {
        $authorized = 0;
        $uid = addNewUser();
        $sid = createSession($uid, $expireTime);
    }
    if ($_POST['token']) {
        // Loginza
        $json = file_get_contents("http://loginza.ru/api/authinfo?token=" . $_POST['token']);
        $decoded = json_decode($json, true);
        $identity = $decoded['identity'];
        if ($identity) {
            $foundUid = searchUid($identity);
            if ($foundUid) {
                // Old user
                $uid = $foundUid;
                $sid = createSession($uid, $expireTime);
            } else {
                // New user
                if ($authorized) {
                    // Create new and switch
                    $uid = addNewUser();
                    $sid = createSession($uid, $expireTime);
                }
                setIdentity($uid, $identity);
            }
            $authorized = 1;
        }
    }

    setcookie($cookieName, $sid, $expireTime);

    $values = array();
    $gid = getCurrentGid($uid, $game);
    if ($gid) {
        $values = loadValues($gid);
    } else {
        $gid = addNewGame($uid);
        $game['gid'] = $gid;
        $game['scheme'] = 0;
        $game['caption'] = "Расчет $gid";
        $game['comments'] = "";
        $game['public'] = 0;
        setGameOptions($gid, $game);
        $values = fillDefaultValues($defaultCounts);
        setValues($gid, $values);
    }
?>
